package com.atguigu.Serivce.Impl;

import com.atguigu.Serivce.DishFlavorService;
import com.atguigu.Serivce.DishService;
import com.atguigu.Utils.R;
import com.atguigu.mapper.CategoryMapper;
import com.atguigu.mapper.DishFlavorMapper;
import com.atguigu.mapper.DishMapper;
import com.atguigu.pojo.Category;
import com.atguigu.pojo.Dish;
import com.atguigu.pojo.DishFlavor;
import com.atguigu.pojo.Dto.DishDto;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Value("${File.basePath}")//图片文件目录
    private String basePath;

    @Transactional//事务管理,因为此操作向两个表添加了，且必须保持要要添加全添加，要不添加都不添加
    @Override
    public R addDishAndFlavor(DishDto dishDto) {
        this.save(dishDto);

        List<DishFlavor> dishFlavors = dishDto.getFlavors();
        dishFlavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));

        dishFlavorService.saveBatch(dishFlavors);

        return R.success("新增菜品成功");
    }


    @Override
    public R page(Integer page, Integer pageSize, String dishName) {
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage =new Page<>();


        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(dishName!=null,Dish::getName, dishName);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishMapper.selectPage(pageInfo,queryWrapper);

        //拷贝pageInfo到dishDtoPage中，除了records,因为records需要经过处理
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

        //因为dishDtoPage.records的List<DishDto>并不支持添加操作，
        // 所以可以创建 List<DishDto>接收数据
        //最后将把该对象赋值给dishDtoPage.records
        List<DishDto> dishDtoList2 = new ArrayList<>();
        //遍历Dish的pageInfo的records,对DishDto的dishDtoPage进行操作
        records.forEach(dish -> {
           //创建DishDto对象
           DishDto dishDto=new DishDto();
           //将dish的值赋给dishDto中
            BeanUtils.copyProperties(dish,dishDto);
            //获得分类对象，并将该对象的名字赋给dishDto的CategoryName
            Category category = categoryMapper.selectById(dish.getCategoryId());
            if(category!=null){
            dishDto.setCategoryName(category.getName());
            }
            dishDtoList2.add(dishDto);
        });
        dishDtoPage.setRecords(dishDtoList2);

        return R.success(dishDtoPage);
    }

    //回显的是dishDto,因为前端需要菜品信息和口味信息
    @Override
    public R reShow(Long id) {
        Dish dish = dishMapper.selectById(id);

        LambdaQueryWrapper<DishFlavor>queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);

        DishDto dishDto = new DishDto();
        dishDto.setFlavors(dishFlavors);

        BeanUtils.copyProperties(dish,dishDto);

        return R.success(dishDto);
    }

    //更新涉及菜品表和口味表两张表，所以要使用事务管理
    @Transactional
    @Override
    public R updateDish(DishDto dishDto) {
        // 更新菜品表
            dishMapper.updateById(dishDto);
        //更新口味表
            //1.先删除与该菜品相关的口味表的记录，因为菜品口味添加或修改为新口味时，旧口味就不该存在
        LambdaQueryWrapper<DishFlavor> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
            //2.添加新口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dishDto.getId());
        });
        dishFlavorService.saveBatch(flavors);

        return R.success("成功修改");

    }

    @Transactional
    @Override//0是停售，1是启售
    public R updateStatus(Long id, Long[] ids) {
        Dish dish = new Dish();
        dish.setStatus(id.intValue());
        LambdaQueryWrapper<Dish> queryWrapper =new LambdaQueryWrapper<>();

        for (Long l : ids) {
            queryWrapper.eq(Dish::getId,l).or();
        }
        dishMapper.update(dish,queryWrapper);
        return R.success("修改成功");
    }

    @Transactional
    @Override
    public R delereDish(Long[] ids) {//相应的口味表也要删除,如果有图片文件，相应的图片文件也要删除

        //删除记录
        LambdaQueryWrapper<Dish> queryWrapper1 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<DishFlavor> queryWrapper2=new LambdaQueryWrapper<>();

        for (Long id : ids) {
            queryWrapper1.eq(Dish::getId,id).or();
            queryWrapper2.eq(DishFlavor::getDishId,id).or();
        }
        //删除图片文件
        List<Dish> dishes = dishMapper.selectList(queryWrapper1);
        for (Dish dish : dishes) {
            String image = dish.getImage();
            File file = new File(basePath + image);
            if (file.exists()) {
                file.delete();
            }
        }


        dishMapper.delete(queryWrapper1);
        dishFlavorService.remove(queryWrapper2);
        return R.success("删除成功");
    }

    @Override
    public R listDish(Long categoryId) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,categoryId);
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);


        List<Dish> dishes = dishMapper.selectList(queryWrapper);
        List<DishDto> dishDtoList =new ArrayList<>();

        dishes.forEach(dish -> {
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            LambdaQueryWrapper<DishFlavor> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> list = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(list);

            dishDtoList.add(dishDto);
        });

        return R.success(dishDtoList);
    }


}
